﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using WF.Common;
using System.Text;
using WF.BusinessObject;

namespace WF.Web
{
    public partial class Login : System.Web.UI.Page
    {
        public string SystemName = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.SystemName = System.Configuration.ConfigurationManager.AppSettings.Get("SystemName").ToString();
                FormsAuthentication.SignOut();
                if (null != this.Session)
                {
                    this.Session.Clear();
                }
                //this.lblVer.Text = System.Reflection.Assembly.Load("WF.Web").GetName().Version.ToString();
            }
        }

        protected void btn_login_Click(object sender, EventArgs e)
        {
            try
            {
                //this.Context.Response.Redirect("default.aspx");
                if (Membership.ValidateUser(UserName.Text, password.Text))
                {
                    SecurityManager sm = new SecurityManager();
                    UserProfile currentUser = sm.GetUserProfile(UserName.Text);
                    Session[SessionKeys.CurrentUser] = currentUser;

                    //if (currentUser.HaveMutilRole)
                    //{
                    //    FormsAuthentication.SetAuthCookie(UserName.Text, false);
                    //    this.MultiLoginView.ActiveViewIndex = 1;
                    //    if (Request.QueryString["ReturnUrl"] != null)
                    //    {
                    //        this.ViewState["ReturnUrl"] = Request.QueryString["ReturnUrl"];
                    //    }
                    //}
                    //else
                    //{
                    if (Request.QueryString["ReturnUrl"] != null)
                    {
                        FormsAuthentication.RedirectFromLoginPage(UserName.Text, false);
                    }
                    else
                    {
                        FormsAuthentication.SetAuthCookie(UserName.Text, false);
                        this.Context.Response.Redirect("default.aspx", true);
                    }
                    //}
                }
                else
                {
                    this.ShowErrorMessage("用户名或密码不正确，请重新输入！", true);
                    //Response.Write("Invalid UserID and Password");
                }
            }
            catch (Exception ex)
            {
                this.HandleException(ex, true);
                this.ShowErrorMessage(ex.Message, true);
            }

        }

        protected void btn_login1_Click(object sender, EventArgs e)
        {
            try
            {
                SecurityManager sm = new SecurityManager();
                UserProfile currentUser = sm.GetUserProfile(UserName.Text);
                Session[SessionKeys.CurrentUser] = currentUser;

                if (Request.QueryString["ReturnUrl"] != null)
                {
                    FormsAuthentication.RedirectFromLoginPage(UserName.Text, false);
                }
                else
                {
                    FormsAuthentication.SetAuthCookie(UserName.Text, false);
                    this.Context.Response.Redirect("default.aspx", true);
                }
            }
            catch (Exception ex)
            {
                this.HandleException(ex, true);
                this.ShowErrorMessage(ex.Message, true);
            }
        }

        public void ShowErrorMessage(string msg)
        {
            ShowErrorMessage(msg, false);
        }

        public void ShowInfoMessage(string msg)
        {
            ShowInfoMessage(msg, false);
        }

        public void ShowErrorMessage(string msg, bool popup)
        {
            if (!popup)
            {
                //this.MessageBar.Visible = true;
                //this.MessageBar.InnerText = "出错信息： " + msg;
            }
            else
            {
                string s = "alert('出错信息： {0}')";
                msg = HttpUtility.HtmlEncode(msg).Replace("'", "\\'");
                s = string.Format(s, msg);
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", s, true);
            }
        }

        public void ShowInfoMessage(string msg, bool popup)
        {
            if (!popup)
            {
                //this.MessageBar.Visible = true;
                //this.MessageBar.InnerText = "提示信息： " + msg;
            }
            else
            {
                string s = "alert('提示信息： {0}')";
                msg = HttpUtility.HtmlEncode(msg).Replace("'", "\\'");
                s = string.Format(s, msg);
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", s, true);
            }
        }

        /// <summary>
        /// 异常处理函数
        /// </summary>
        /// <param name="ex">异常</param>
        /// <param name="popup">是否弹出窗口</param>
        public void HandleException(Exception ex, bool popup)
        {
            if (null != ex)
            {

                //如果异常类型是业务异常或者业务异常派生出来的异常，则不记日志，


                //如果是其他异常记录日志


                if ((null != ex.InnerException) && (!(ex.InnerException is BusinessException)))
                {
                    //输出日志
                    TraceHelper.TraceError(ex.ToString());
                }

                //取出所有的内部异常信息
                StringBuilder builder = new StringBuilder();
                //builder.AppendFormat("[{0}] ", ex.Message);
                for (Exception exception = ex; exception != null; exception = exception.InnerException)
                {
                    if (exception is BusinessException)
                    {
                        builder.Remove(0, builder.Length);
                        builder.AppendFormat("[{0}] ", exception.Message);
                        break;
                    }
                    else
                    {
                        builder.AppendFormat("[{0}] ", exception.Message);
                    }
                }

                //显示
                ShowErrorMessage(builder.ToString(), popup);
            }
        }

        /// <summary>
        /// ObjectDataSource异常处理函数
        /// </summary>
        /// <param name="e"></param>
        /// <param name="popup">是否弹出窗口</param>
        public void HandleException(ObjectDataSourceStatusEventArgs e, bool popup)
        {
            if (null != e.Exception)
            {
                HandleException(e.Exception, popup);
                e.ExceptionHandled = true;
            }
            else
            {
                ShowInfoMessage("操作成功", false);
            }
        }

        protected void btnSelectRole_Click(object sender, EventArgs e)
        {
            SessionManager sm = new SessionManager();
            UserProfile currentUser = sm.CurrentUser;
            //currentUser.RoleID = currentUser.Roles[ddlRoleList.SelectedIndex].RoleId;
            //currentUser.RoleName = currentUser.Roles[ddlRoleList.SelectedIndex].RoleName;
            //currentUser.DeptID = currentUser.Roles[ddlRoleList.SelectedIndex].DepartmentID;
            //currentUser.DeptName = currentUser.Roles[ddlRoleList.SelectedIndex].DepartmentName;
            //currentUser.DeptPath = currentUser.Roles[ddlRoleList.SelectedIndex].DeptPath; ;
            //currentUser.PositionID = currentUser.Roles[ddlRoleList.SelectedIndex].PositionID;
            //currentUser.PositionName = currentUser.Roles[ddlRoleList.SelectedIndex].PositionName;

            if (null != this.ViewState["ReturnUrl"])
            {
                this.Context.Response.Redirect((string)this.ViewState["ReturnUrl"]);
            }
            else
            {
                this.Context.Response.Redirect("default.aspx");
            }
        }

        protected void RoleSelectView_Activate(object sender, EventArgs e)
        {
            //this.ddlRoleList.Items.Clear();
            //SessionManager sm = new SessionManager();
            //UserProfile currentUser = sm.CurrentUser;
            //foreach (RoleAssign item in currentUser.Roles)
            //{
            //    ListItem listItem = new ListItem(item.DepartmentName + " " + item.RoleName);
            //    this.ddlRoleList.Items.Add(listItem);
            //}
            //this.ddlRoleList.SelectedIndex = 0;
        }
    }
}